// ==UserScript==
// @name         ecs - test
// @namespace    http://tako.tampermonkey.net/
// @version      0.1
// @description  test
// @author       tako
// @match        *://*/*
// @run-at       context-menu
// @grant        GM_xmlhttpRequest
// ==/UserScript==
(function () {
  'use strict';
  if (typeof GM_xmlhttpRequest === 'undefined') {
    // 不在油猴环境中
    console.error('此脚本需要在Tampermonkey/Greasemonkey环境中运行');
    return;
  }

  (async () => {
    try {
      const { appId, menuId } = getAppIdAndMenuId();
      const token = localStorage.getItem('console_TOKEN');
      console.log('appId:', appId);
      console.log('MenuId:', menuId);
      console.log('token:', token);

      // mdd
      const mddAppId = 'c76ef194385e11eb9f43c90043244155';
      if (appId != mddAppId) {
        alert('非mdd应用，请切换到mdd应用');
        return;
      }

      const formSetting = await getFormSetting(menuId,token,appId);
      console.log('get-forms-settings-by-formIds:', formSetting);

      // 控制台应用
      const console_tabs_list = document.querySelector('.console-tabs-list');
      if (!isVisible(console_tabs_list)) {
        console.log('.console-tabs-list 不存在');
        return;
      }

      // 找到当前应用
      const all_console_tabs_item = console_tabs_list.querySelectorAll('div');
      const active_console_tabs_item = Array.from(all_console_tabs_item).filter(div => {
        const style = window.getComputedStyle(div);
        return style.visibility === 'visible';
      });

      const mr_form_tabs = document.querySelector('.mr-form-tabs');
      console.log('mr_form_tabs:', mr_form_tabs);
    } catch (err) {
      console.error('失败:', err);
    }
  })();


  function isVisible(element) {
    if (element) {
      const style = window.getComputedStyle(element);
      if (style.display === 'none') {
        return false;
      } else {
        return true;
      }
    }

    alert('元素不存在');
    return false;
  }

  /**
   * 获取appId和menuId
   * @returns {object} appIdAndMenuId
   * @property {string} appId
   * @property {string} menuId
   */
  function getAppIdAndMenuId() {
    // 获取当前URL
    const currentUrl = window.location.href;
    // 解析URL
    const url = new URL(currentUrl);
    // 解析hash部分: #/home/app/c76ef194385e11eb9f43c90043244155?menuId=a2e9f2a035f611eba12e05f7f2349621
    const [hashPath, params] = url.hash.split('?');
    // 提取appId
    const appId = hashPath.split('/')[3];
    // 提取menuId参数
    const menuId = new URLSearchParams(params).get('menuId'); // "11ed6b1b9420f420bd7ceb5eb09eddb4"
    // 返回结果
    return { appId, menuId };
  }

  function gmRequest(options) {
    return new Promise((resolve, reject) => {
      GM_xmlhttpRequest({
        ...options,
        onload: resolve,
        onerror: reject
      });
    });
  }

  /**
   * 获取表单设置
   * @param {string} formId - 表单id
   * @param {string} token - token
   * @param {string} appId - appId
   * @returns {object} formSetting
   * @property {string} cubeCode
   * @property {string} cubeId
   * @property {string} cubeName
   * @property {list} dims
   * @property {list} dimsList
   */
  async function getFormSetting(formId, token, appId) {
    try {
      const res = await gmRequest({
        method: 'GET',
        url: `/mdd/bff/forms/get-forms-settings-by-formIds?formIds=${formId}`,
        headers: {
          'Logintoken': token,
          'appId': appId
        }
      });
      const resJSON = JSON.parse(res.responseText);
      if (resJSON.success && !resJSON.success) {
        console.error("获取表单设置失败:", resJSON.message);
        return;
      }
      return resJSON[0];
    } catch (err) {
      console.error('获取表单设置失败:', err);
      return;
    }
  }

  
  async function pageDimMembers(formId, token, appId) {
    try {
      const res = await gmRequest({
        method: 'POST',
        url: `/mdd/mdd/bff/forms/pageDimMembers/paramsv2`,
        headers: {
          'Logintoken': token,
          'appId': appId
        },
        data: JSON.stringify({
          formId,
          "adHocFlag": false,
          "taskdistributionDetailId": "",
          "changeFlag": false,
          "pageSize": 5000,
          "taskMemberFlag": false,
          "taskId": "",
          "apvlInstanceId": "",
          "dtos": [
            {
              "dimId": "11ed33f3f85cbcf39ad4cbd389354227",
              "dimMemberExps": "{\"categoryOrder\":[\"member\",\"attr\",\"level\",\"variable\",\"rollRule\",\"subset\"],\"member\":[{\"memberName\":\"杭州绿城\",\"memberTypeValue\":\"self\",\"memberId\":\"11ed349b108d63e39ad4a778f26e8ddb\"},{\"memberName\":\"北京元年\",\"memberTypeValue\":\"self\",\"memberId\":\"11ed3e146545ba9e9ad427166be38d34\"}],\"union\":false,\"attrUnion\":false,\"allMember\":false}",
              "realData": true,
              "limit": 10000,
              "keepGeneration": true,
              "pageDimShowType": "",
              "disableParentSelection": false
            },
            {
              "dimId": "11ed33f3e82f32289ad46de355a304df",
              "dimMemberExps": "{\"categoryOrder\":[\"member\",\"attr\",\"level\",\"variable\",\"rollRule\",\"subset\"],\"member\":[],\"union\":false,\"attrUnion\":false,\"allMember\":true}",
              "realData": true,
              "limit": 10000,
              "keepGeneration": true,
              "pageDimShowType": "",
              "disableParentSelection": false
            }
          ]
        })
      });
      const resJSON = JSON.parse(res.responseText);
      if (resJSON.success && !resJSON.success) {
        console.error("获取表单设置失败:", resJSON.message);
        return;
      }
      return resJSON[0];
    } catch (err) {
      console.error('获取表单设置失败:', err);
      return;
    }
  }

})();